package com.bracelet.service;

import com.bracelet.beans.User;
import com.bracelet.beans.UserExample;
import com.bracelet.dao.UserMapper;
import com.bracelet.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MethodService {
    @Autowired
    UserMapper mapper;
    public  User FindUser(User user){
        User user1 = null;
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(user.getUsername());
        //criteria.andPasswordEqualTo(user.getPassword());
        List<?> list = mapper.selectByExample(example);
        if(list.size() == 0){
            return null;
        }else{
            user1 = (User) list.get(0);
            String password = user.getPassword();
            password = password + user1.getSalt();
            password = MD5Utils.MD5Encode(password,"UTF-8",true);
            if(password.equals(user1.getPassword())) {
                return user1;
            }
            else {
                return null;
            }
        }
    }
    public  boolean SaveUser(User user){
        if(isSame(user)){
            return false;
        }
        String salt = MD5Utils.produceSalt();
        user.setSalt(salt);
        String password = user.getPassword();
        password = password + salt;
        password = MD5Utils.MD5Encode(password,"UTF-8",true);
        user.setPassword(password);
        try {
           mapper.insertSelective(user);
       }catch (Exception e){
           return false;
       }
       return true;
    }
    public boolean isSame(User user){
        User user1 = null;
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(user.getUsername());
        List<?> list = mapper.selectByExample(example);
        if(list.size() > 0){
            return true;
        }else{
            return false;
        }
    }
}
